#include "trie.h"
#include <stdio.h>
#include <stdlib.h>

void TrieCreate (trie * T)
{
	int i;
	trie_no * aux;
	aux = (trie_no *) malloc (sizeof(trie_no));
	if (aux != NULL)
	{
		aux->isword = 0;
		for (i = 0; i < 26; i++)
			aux->child[i] = NULL;
		T->words = 0;
		T->root = aux;
	}
}

void TrieDestroy (trie * T)
{
	TrieNoDestroy(T->root);
}

void TrieNoDestroy (trie_no * N)
{
	int i;
	for (i = 0; i < 26; i++)
	{
		if (N->child[i] != NULL)
			TrieNoDestroy(N->child[i]);
	}
	free(N);
}

void TrieAdd (trie * T, char * str)
{
	int i;
	trie_no * it = T->root;
	for (i = 0; str[i] != '\0'; i++)
	{
		if (it->child[str[i]-'a'] == NULL)
		{
			trie_no * aux = (trie_no *) malloc(sizeof(trie_no));
			int j;
			for (j = 0; j < 26; j++)
				aux->child[j] = NULL;
			aux->isword = 0;
			it->child[str[i]-'a'] = aux;
		}
		it = it->child[str[i]-'a'];
	}
	if (!it->isword)
	{
		T->words++;
		it->isword = 1;
	}
}

int TrieFind (trie * T, char * str)
{
	int i;
	trie_no * it = T->root;
	for (i = 0; str[i] != '\0'; i++)
	{
		if (it->child[str[i]-'a'] == NULL)
			return 0;
		it = it->child[str[i]-'a'];
		if (it->isword)
			return 1;
	}
	return 0;
}

void TrieRemove (trie * T, char * str)
{
	int i;
	trie_no * it = T->root;
	for (i = 0; str[i] != '\0'; i++)
	{
		if (it->child[str[i]-'a'] == NULL)
			return;
		it = it->child[str[i]-'a'];
		if (it->isword)
		{
			T->words--;
			it->isword = 0;
		}
	}
}
